package autotd.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

//Simple java client
public class SimpleClient implements NetworkProtocol {

	protected Socket socket;
	protected PrintWriter out;
	protected BufferedReader in;
	
	int i = 0;
	
	public SimpleClient() {
		initialise();
	}
	
	public void initialise(){
		
		try {
			socket = new Socket("localhost", DEFAULT_PORT_NUMBER);
			out = new PrintWriter(socket.getOutputStream());
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			//Wait for confirmation of connection
			while(!in.readLine().equals(CONNECTED_RESPONSE)) {}
			sendServer(COMMANDER_REQUEST);
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	public void placeTower(int x, int y, String type) {
		String command = CMD_PLACE_TOWER + CMD_DELIM;
		command = command + x + " ";
		command = command + y + " ";
		command = command + type;
		sendServer(command);
		
		if (receiveServer().equals(ACK)){
			System.out.println("Place Tower Success");
		} else {
			System.out.println("Place Tower Fail");
		}
	}
	
	public void fireTower(int x, int y, int monsterId) {
		String command = CMD_FIRE_TOWER + CMD_DELIM;
		command = command + x + " ";
		command = command + y + " ";
		command = command + monsterId;
		sendServer(command);
		
		if (receiveServer().equals(ACK)){
			System.out.println("Fire Tower Success");
		} else {
			System.out.println("Fire Tower Fail");
		}
	}
	
	public void tick(int t) {
		String command = CMD_TICK + CMD_DELIM;
		command = command + t;
		sendServer(command);
		
		if (receiveServer().equals(ACK)){
			System.out.println("Tick Success");
		} else {
			System.out.println("Tick Fail");
		}
	}
	
	public String queryPlayer() {
		String command = CMD_QUERY_PLAYER + CMD_DELIM;
		sendServer(command);
		return receiveServer();
	}
	
	public String queryMap() {
		String command = CMD_QUERY_MAP + CMD_DELIM;
		sendServer(command);
		return receiveServer();
	}
	
	public String queryMonsters() {
		String command = CMD_QUERY_MONSTERS + CMD_DELIM;
		sendServer(command);
		return receiveServer();
	}
	
	public String queryTowers() {
		String command = CMD_QUERY_TOWERS + CMD_DELIM;
		sendServer(command);
		return receiveServer();
	}
	
	public String queryTowerTypes() {
		String command = CMD_QUERY_TOWER_TYPES + CMD_DELIM;
		sendServer(command);
		return receiveServer();
	}
	
	public void sendServer(String communication) {
		System.out.println("sending " + i++);
		out.println(communication);
		out.flush();
		System.out.println("flushed");
	}
	
	public String receiveServer() {
		
		try {
			return in.readLine();
		} catch(IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
